package biometria.client;

import biometria.client.service.LoginService;
import biometria.client.ui.LoginContainer;
import biometria.shared.User;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Biometria implements EntryPoint {

	LoginContainer loginContainer;
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		String sessionID = Cookies.getCookie("sid");
	    if (sessionID != null) {
	    	checkWithServerIfSessionIdIsStillLegal(sessionID);
	    } else {
	    	displayLoginBox();
	    }
	}

	private void checkWithServerIfSessionIdIsStillLegal(String sessionID) {
		LoginService.Util.getInstance().loginFromSessionServer(
				new AsyncCallback<User>() {
					@Override
					public void onFailure(Throwable caught) {
						displayLoginBox();
					}

					@Override
					public void onSuccess(User result) {
						if (result == null) {
							displayLoginBox();
						} else {
							if (result.getLogged()) {
								buildUI();
							} else {
								displayLoginBox();
							}
						}
					}

				});
	}
	
	private void displayLoginBox() {
		loginContainer = new LoginContainer();
		loginContainer.displayLoginContainer();
	}
	
	public static void buildUI() {
		RootPanel.get().clear();
		clear(RootPanel.getBodyElement());
	}
	
	private static void clear(Element parent) {
	        Element firstChild;
	        while((firstChild = DOM.getFirstChild(parent)) != null) {
	                DOM.removeChild(parent, firstChild);
	        }
	}
	

}
